package com.tz.cartelo.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.view.WindowManager;

import com.tz.cartelo.R;
import com.tz.common.util.ToastUtil;
import com.tz.common.view.SystemBarTintManager;

import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Base activity
 * Created by Chris on 16/7/19.
 */
public abstract class BaseActivity extends FragmentActivity {
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.tz.scoursand.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    private boolean mIsCurrentNetworkConnected = true;
    private SweetAlertDialog mLoadingDialog;

    //Return layout id
    protected abstract int getLayoutResId();

    //Initial view controls and data
    protected abstract void init();

    //Initial title view controls and data
    protected abstract void initTitle();

    //Set listeners.
    protected void setListener() {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        registerMessageReceiver();  // used for receive msg
        registerReceiver();
        initTitle();
        init();
        setListener();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.main_color);//通知栏所需颜色
        }
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                System.out.println("Main=jpush messge=:" + messge);
                System.out.println("Main=jpush extras=:" + extras);
            }
        }
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        if (null != mReceiver)
            registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mReceiver) {
            unregisterReceiver(mReceiver);
        }
        unregisterReceiver(mMessageReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                boolean connected = isNetworkConnected();
                if (mIsCurrentNetworkConnected) {   //断开
                    if (!connected)
                        showNetworkConnection(false);
                } else {    //连接
                    if (connected) {
                        showNetworkConnection(true);
                        onConnectRefresh();
                    }
                }
                mIsCurrentNetworkConnected = connected;
            }
        }
    };

    protected void onConnectRefresh() {
        //网络连接时，刷新页面
    }

    protected boolean isNetworkConnected() {
        return isNetworkConnected(this);
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (mConnectivityManager != null) {
                NetworkInfo mNetworkInfo = mConnectivityManager
                        .getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable();
                }
            }
        }
        return false;
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected boolean showNetworkConnection(boolean isConnected) {
        showToast(isConnected ? R.string.network_connected : R.string.network_disconnected);
        return false;
    }

    protected void showToast(int resId) {
        ToastUtil.showText(this, resId);
    }

    protected void showToast(String msg) {
        ToastUtil.showText(this, msg);
    }

    protected void switchActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent(this, cls);
        if (extras != null)
            intent.putExtras(extras);
        startActivity(intent);
    }

    protected void switchActivity(Class<?> cls, Bundle extras, int flags) {
        Intent intent = new Intent(this, cls);
        if (extras != null)
            intent.putExtras(extras);
        intent.setFlags(flags);
        startActivity(intent);
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras) {
        switchActivity(cls, extras);
        finish();
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras, int flags) {
        switchActivity(cls, extras, flags);
        finish();
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras) {
        Intent intent = new Intent(this, cls);
        if (extras != null)
            intent.putExtras(extras);
        startActivityForResult(intent, requestCode);
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras, int flags) {
        Intent intent = new Intent(this, cls);
        if (extras != null)
            intent.putExtras(extras);
        intent.setFlags(flags);
        startActivityForResult(intent, requestCode);
    }

    protected void finishActivityForResult() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void finishActivityWithExtra(Bundle extras) {
        Intent intent = new Intent();
        if (extras != null)
            intent.putExtras(extras);
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void switchActivityReorder2Front(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }

    protected void switchFragment(Fragment fragment, int resId, Bundle extras) {
        if (extras != null)
            fragment.setArguments(extras);
        getSupportFragmentManager().beginTransaction()
                .replace(resId, fragment).commit();
    }

    public void showProgressDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
            mLoadingDialog.setCancelable(true);
            mLoadingDialog.setTitleText(getString(R.string.loading));
        }
        mLoadingDialog.show();
    }

    public void dismissProgressDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }
}
